#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<algorithm>
using namespace std;
using ll = long long;
int p, n;
ll qmi(ll a, ll k)
{
    ll res = 1;
    while (k)
    {
        if (k & 1) res = res * a % p;
        k >>= 1;
        a = a * a % p;
    }
    return res;
}
ll C(ll a, ll b)
{
    ll res = 1;
    for (ll i = 1, j = a; i <= b; i++, j--)
    {
        res = res * j % p;
        res = res * qmi(i, p - 2) % p;
    }
    return res;
}
ll lucas(ll a, ll b)
{
    if (a < p && b < p) return C(a, b);
    return C(a % p, b % p) * lucas(a / p, b / p) % p;
}
int main()
{
    cin >> n;
    while (n--)
    {
        ll a, b;
        cin >> a >> b >> p;
        cout << lucas(a, b) << endl;
    }
    return 0;
}